package handler

import (
	"github.com/gin-gonic/gin"
	"logi-whse/cache"
	"logi-whse/kpg"
	"logi-whse/model"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误,禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != kpg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func UserNodeAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.UserNode{
		Uid: uid,
		Nid: nid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分配成功",
	})
	return
}
func UserNode(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN user_nodes ON nodes.id=user_nodes.nid
		WHERE user_nodes.uid=1
	*/
	var data []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN user_nodes ON nodes.id=user_nodes.nid").
		Where("user_nodes.uid=?", uid).
		Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
